package com.cn.exception;

import com.cn.response.Result;
import com.cn.response.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * 功能描述: <br>
 *
 * @program: xg-prant
 * @description: 全局异常处理类
 * @author: Mr.TYJ
 * @create: 2022-03-02 17:57
 **/
@Slf4j
@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody
public class GlobalExceptionHandler {

    @ExceptionHandler(ArithmeticException.class)
    public Result arithmeticException(ArithmeticException e){
        e.printStackTrace();
        log.info("算数异常"+e.getMessage());
       return Result.error(ResultCode.ARITHMETIC_EXCEPTION);
    }

    @ExceptionHandler(NullPointerException.class)
    public Result nullPointerException(NullPointerException e){
        e.printStackTrace();
        return Result.error(ResultCode.NULL_POINTER_EXCEPTION);
    }

    @ExceptionHandler(ArrayIndexOutOfBoundsException.class)
    public Result arrayIndexOutOfBoundsException(ArrayIndexOutOfBoundsException e){
        e.printStackTrace();
        return Result.error(ResultCode.ARRAY_INDEX_OUT_BOUNDS_EXCEPTION);
    }

    @ExceptionHandler(Exception.class)
    public Result exception(Exception e){
        e.printStackTrace();
        return Result.error(ResultCode.UNKNOWN_EXCEPTION);
    }

//    处理业务异常
    @ExceptionHandler(BusinessException.class)
    public Result businessException(BusinessException e){

        return Result.error().code(e.getCode()).message(e.getErrMsg());
    }

}
